# -*-coding:utf-8-*-
import json, requests, os, time, requests
from redis import StrictRedis
from ITAdmin.settings import REDIS_URL, SALT_USER, SALT_PASSWORD, SALT_SERVER


def get_salt_token():
    r = StrictRedis.from_url(REDIS_URL)
    if r.exists('salttoken'):
        result = eval(r.get('salttoken'))
        if result['expire'] >  int(time.time()):
            return result['token']
        else:
            token = salt_login()
            r.set('salttoken', token)
            return token['token']
    else:
        token = salt_login()
        r.set('salttoken', token)
        return token['token']


def get_data(url, params, headers):
    send_data = json.dumps(params)
    request = requests.post(url, data=send_data, headers=headers, verify=False)
    response = request.json()
    result = dict(response)
    return result['return'][0]


def salt_login():
    headers = {"Content-type": "application/json"}
    login_url = os.path.join(SALT_SERVER, 'login')
    login_params = {'username': SALT_USER, 'password': SALT_PASSWORD, 'eauth': 'pam'}
    res = get_data(login_url, login_params, headers)
    result = dict()
    result['token'] = res['token']
    result['expire'] = int(res['expire'])
    return result


def get_minion(token):
	headers = {"Content-type": "application/json", 'X-Auth-Token': token}
	params = {'fun': 'key.list_all','client':'wheel'}
	res = get_data(SALT_SERVER, params, headers)
	result = dict()
	result['minion'] = res['data']['return']['minions']
	result['minions_pre'] = res['data']['return']['minions_pre']
	return result

def del_minion(token, minion_ids):
	headers = {"Content-type": "application/json", 'X-Auth-Token': token}
	params = {'fun': 'key.delete','client':'wheel', 'match': minion_ids}
	res = get_data(SALT_SERVER, params, headers)
	return res['data']['success']

def add_minion(token, minion_ids):
	headers = {"Content-type": "application/json", 'X-Auth-Token': token}
	params = {'fun': 'key.accept','client':'wheel', 'match': minion_ids}
	res = get_data(SALT_SERVER, params, headers)
	return res['data']['success']